const Router = require('koa-router');
const router = new Router();
const tools = require('../tools/tool')
const {db, QueryTypes, Op} = require("../models/db");
const pageParams = require("../tools/cols");
const {setTreeTableCode} = require("../tools/treeTableSave");

router.post('/page/list', async ctx => {
    let whichPage = ctx.request.body.whichPage;
    let currentPage = ctx.request.body.currentPage ?ctx.request.body.currentPage:1;
    let pageSize = ctx.request.body.pageSize?ctx.request.body.pageSize:200;
    let excel = ctx.request.body.excel?ctx.request.body.excel:0;
    let sort = ctx.request.body.sort
    let offset = (currentPage - 1) * pageSize;
    if(!whichPage) return ctx.err('没有模型名')
    let params = pageParams(ctx, tools) // cols文件中的列配置
    let columns = params.columns
    let where = combSearch(params, ctx)
    let sql = params.sql
    if(where.length > 0) {
        sql = sql + ' and ' + where.join(' and ')
    }
    let orderBy = ''
    if(sort && sort.length > 0) {
        let ord = []
        sort.map(o => {
            ord.push(` ${o.field} ${o.order}`)
        })
        orderBy = ` order by ${ord.join(',')} `
    }
    else {
        orderBy = (params.order ? params.order : ' order by id desc ')
    }
    sql = sql.replaceAll('$tid', ctx.user.tenantId)
    sql = sql.replaceAll('$uid', ctx.user.id)
    if(excel) {
        sql += orderBy
        let ret = await db.query(sql, {type: QueryTypes.SELECT})
        return await tools.exportOut(params, ret, ctx)
    }
    else {
        let countModel = await db.query( `select count(*) count from (${sql}) a`, {type: QueryTypes.SELECT, plain: true} );
        let total = parseInt(countModel.count);
        // 默认分页
        sql += orderBy
        if(typeof params.allowPage === 'undefined' || params.allowPage) {
            sql += " offset " + offset + " rows fetch next " + pageSize + ' rows only; '
        }
        let ret = await db.query(sql, {type: QueryTypes.SELECT });
        return ctx.suc('', {
            total,
            list: ret,
            columns: tools.obj2str(columns)
        })
    }
})

// 表单配置
router.post('/page/getFormRule', async ctx => {
    let sets = pageParams(ctx, tools)
    if(!sets) return ctx.err('没有数据模型')
    sets = tools.obj2str(sets.form)
    return ctx.suc('', sets)
})
// 搜索表单
router.post('/page/pageParams', async ctx => {
    let sets = pageParams(ctx, tools)
    if(!sets) return ctx.err('没有数据模型')
    sets.columns.map(row => {
        if(row.filter) {
            row.filterRender = {name: 'FExtend'}
            row.filters = [{data: {vals: [], sVal: '', fMenu: '', f1Type:'', f1Val: '', fMode: 'and', f2Type: '', f2Val: ''}}]
        }
    })
    sets.search.rule.map(row => {
        if(row.props) {
            row.props.clearable = true
        }
        else {
            row.props = {
                clearable: true
            }
        }
    })
    sets.form.rule.map(row => {
        if(row.props) {
            row.props.clearable = true
        }
        else {
            row.props = {
                clearable: true
            }
        }
    })
    sets = tools.obj2str(sets)
    return ctx.suc('', sets)
})
// 表格列
router.post('/page/columns', async ctx => {
    let sets = pageParams(ctx, tools)
    if(!sets) return ctx.err('没有数据模型')
    sets = tools.obj2str(sets.form)
    return ctx.suc('', sets)
})

// 表单保存
router.post('/page/saveForm', async ctx => {
    let formData = ctx.request.body.formData;
    let par = pageParams(ctx, tools)
    let form = par.form
    if(form.mod) {
        let checkindex = await checkIndex(form.mod, ctx)
        if(checkindex) return ctx.err(checkindex)
        await setFormData(form.mod, formData, ctx)
        if(formData.id) {
            if(ctx.request.body.whichPage === 'goods') {
                let mo = await db.models['goods'].findOne({
                    where: {
                        tenantId: ctx.user.tenantId,
                        id: formData.id
                    }
                })
                
                if(mo.spec != formData.spec) {
                    let hasdata = await db.models['invoiceInfo'].count({
                        where: {
                            tenantId: ctx.user.tenantId,
                            invId: formData.id
                        }
                    })
                    if(hasdata) {
                        return ctx.err('商品已有出入库记录，不能再修改规格')
                    }
                }
                await db.transaction(async t=>{
                    await db.models[form.mod].update(
                        formData, {
                            where: {
                                id: formData.id
                            }
                        },
                        {transaction: t}
                    )
                })
                return ctx.suc('保存成功', formData)
            }
            else {
                await db.transaction(async t=>{
                    await db.models[form.mod].update(
                        formData, {
                            where: {
                                id: formData.id
                            }
                        },
                        {transaction: t}
                    )
                })
                return ctx.suc('保存成功', formData)
            }
        }
        else {
            let mode = await db.transaction(async  t => {
                let m = await db.models[form.mod].create(formData, {transaction: t})
                return m
            })

            return ctx.suc('新增成功', mode)
        }
    } else {
        return ctx.err('没有找到数据模型名称')
    }
})
// 删除
router.post('/page/del', async ctx => {
    let ids = ctx.request.body.ids;
    let par = pageParams(ctx, tools)
    let form = par.form
    if(form.mod) {
        let attr = db.models[form.mod].getAttributes()
        let soft = false
        let update = {}
        for(let i in attr) {
            if(i === 'dby') {
                soft = true
                update.dby = ctx.user.id
            }
            if(i === 'dt') {
                soft = true
                update.dt = tools.getTime()
            }
            if(i === 'isDel') {
                soft = true
                update.isDel = 1
            }
        }
        await db.transaction(async t => {
            for (let i = 0; i < ids.length; i++) {
                let model = await db.models[form.mod].findOne({
                    where: {
                        id: ids[i]
                    }
                })

                if(soft) {
                    await model.update(update, {transaction: t})
                } else {
                    await model.destroy({transaction: t})
                }
            }
        })

        return ctx.suc('已删除,' + ids.length)
    } else {
        return ctx.err('没有找到数据模型名称')
    }
})

router.post('/page/getRouteByField', async ctx => {
    let field = ctx.request.body.field;
    let routeName = ctx.request.body.routeName;
    let value = ctx.request.body.value;
    let row = ctx.request.body.row;
    if(!field) return ctx.err('没有模型名')
    let route = {
        name: '/#/'
    }
    // let menu = await db.models['menu'].findOne({
    //     where: {
    //         routeId: routeName
    //     }
    // })
    if(field === 'billNo' || field === 'srcBillNo') {
        route.name = route.name + getRouteByBillNo(value)
        route.query = {
            billNo: value
        }
        route.width = 1400
        route.height = 700
        route.title = '单据'
    }
    if (routeName === 'reportacc' || routeName === 'customerbills') {
        route.name = route.name + 'bandc'
        let bd = row.billDate.split('.')
        route.query = {
            field,
            page: routeName,
            id: row.id,
            beginDate: bd[0],
            endDate: bd[1],
            billDate: row.billDate
        }
        route.width = 1400
        route.height = 700
        route.title = '单据'
    }
    if(routeName === 's-ins' && field === 'hxAmount') {
        route.name = route.name + 'bandc'
        route.query = {
            field,
            page: routeName,
            id: row.id
        }
        route.width = 1400
        route.height = 700
        route.title = '单据'
    }
    if(routeName === 'kcye') {
        route.name = route.name + 'gdetail'
        route.query = row
        route.page = 'kcye'
        route.width = 1400
        route.height = 700
        route.title = '单据'
    }
    // 科目余额明细
    if(routeName === 'kmye') {
        if(field === 'price1') {
            route.title = '借方发生'
        }
        if(field === 'price2') {
            route.title = '贷方发生'
        }
        route.name = route.name + 'kmyemx'
        route.page = 'kmyemx'
        route.query = row
        route.width = 1400
        route.height = 700
    }

    return ctx.suc('', route)
})

router.post('/page/getSalesByBuId', async ctx => {
    let buId = ctx.request.body.buId
    let invoidc = await db.query(`
     select id,name from admin where id in(select DISTINCT salesId from invoice where 
     buId=${buId} and tenantId=${ctx.user.tenantId})
     `,{type: QueryTypes.SELECT})
    return ctx.suc('', invoidc)
})
router.post('/page/psApiUrl', async ctx => {
    return ctx.suc('', 'https://v3.sanzhiyun.cn/#/deliver')
})

// 组合要保存的数据
const setFormData = async (modName, formData, ctx) => {
    let attrs = db.models[modName].getAttributes()
    for(let i in attrs) {
        if(i === 'tenantId') {
            formData.tenantId = ctx.user.tenantId
        }
        if(tools._.endsWith(i, 'Id')) {
            if(!formData[i]) formData[i] = null
        }
        if(i === 'pinYin') {
            formData.pinYin = formData.name ? tools.py(formData.name) : null
        }
        if(i === 'code') {
            if(isTree(attrs) && !formData.id) {
                // 新增设置树形表的code
                await setTreeTableCode(modName, formData, ctx)
            }
        }
        if(i === 'ct') {
            if(!formData.id) formData.ct = tools.getTime()
        }
        if(i === 'ctime') {
            if(!formData.id) formData.ctime = tools.getTime()
        }
        if(i === 'ut') {
            formData.ut = tools.getTime()
        }
        if(i === 'utime') {
            formData.utime = tools.getTime()
        }
        if(i === 'cby') {
            if(!formData.id) formData.cby = ctx.user.id
        }
        if(i === 'uby') {
            formData.uby = ctx.user.id
        }
    }
    // 设置快速搜索内容
    hasQuick(attrs, formData)
}
const isTree = (attrs) => {
    for(let i in attrs) {
        if(i === 'pid') return true
    }
    return false
}
const hasQuick = (attrs, formData) => {
    let quick = []
    for(let i in attrs) {
        if(i === 'quick') {
            for(let i in formData) {
                if(formData[i]) {
                    quick.push(formData[i])
                }
            }
        }
    }
    if(quick.length > 0) formData.quick = quick.join(',')
    return false
}
// 检测索引
const checkIndex = async (modName, ctx) => {
    // 通过返回false  错误返回错误信息
    let indexes = db.models[modName].getIndexes()
    let formData = ctx.request.body.formData;
    // 检测索引
    if(indexes.length > 0) {
        for (let x = 0; x < indexes.length; x++) {
            let row = indexes[x]
            if(row.unique) {
                let where = {}
                let hastent = false
                for (let i = 0; i < row.fields.length; i++) {
                    if(row.fields[i] === 'tenantId') {
                        hastent = true
                    }else {
                        // 如果索引中的字体有上传的值
                        if(typeof row.fields[i] !== 'undefined' && formData[row.fields[i]])
                            where[row.fields[i]] = formData[row.fields[i]]
                    }
                }

                if(!tools.xe.isEmpty(where)) {
                    if(hastent) where.tenantId = ctx.user.tenantId
                }
                if (formData.id) {
                    if(!tools.xe.isEmpty(where)) {
                        where.id = {
                            [Op.ne]: formData.id
                        }
                    }
                }
                if(!tools.xe.isEmpty(where)) {
                    let c = await db.models[modName].count({
                        where: where
                    })
                    if(c > 0) {
                        return row.name
                    }
                }
            }
        }
    }
    return false
}

const combSearch = (params, ctx) => {
    let cols = params.search.rule
    let formData = ctx.request.body.formData;
    let where = []
    if(formData.searchTxt) {
        let w = []
        cols.map(row =>　{
            if(row.quick) {
                w.push(`${row.field} like '%${formData.searchTxt}%'`)
            }
        })
        if(w.length > 0) {
            where.push(`(${w.join(' or ')})`)
        }
    }
    else {
        for (let i in formData) {
            if (i && typeof formData[i] !== 'undefined' && formData[i] !== null && formData[i] !== '') {
                cols.map(s => {
                    if (s.field === i && s.op) {
                        if(tools.xe.indexOf(params.sql, '$'+s.field) !== -1) {
                            params.sql = params.sql.replaceAll('$'+s.field, formData[i])
                        }
                        else {
                            let w = s.op.replaceAll('$tid', ctx.user.tenantId)
                                .replaceAll('$uid', ctx.user.id)
                                .replaceAll('$', formData[i])
                            where.push(`${s.field} ${w}`)
                        }
                    }
                })
            }
        }
    }
    return where
}

const getRouteByBillNo = (billNo) => {
    if(billNo.indexOf('SK') === 0) {
        return 'receipt'
    }
    if(billNo.indexOf('XS') === 0) {
        return 's-in'
    }
    if(billNo.indexOf('XT') === 0) {
        return 's-out'
    }
    if(billNo.indexOf('XH') === 0) {
        return 's-t'
    }
    if(billNo.indexOf('FK') === 0) {
        return 'payment'
    }
    if(billNo.indexOf('QTRK') === 0) {
        return 'oin'
    }
    if(billNo.indexOf('QTCK') === 0) {
        return 'oout'
    }
    if(billNo.indexOf('CG') === 0) {
        return 'pur-in'
    }
    if(billNo.indexOf('CT') === 0) {
        return 'pur-out'
    }
    if(billNo.indexOf('YSK') === 0) {
        return 'yusk'
    }
    if(billNo.indexOf('YFK') === 0) {
        return 'yufk'
    }
    if(billNo.indexOf('YSG') === 0) {
        return 'yussp'
    }
    if(billNo.indexOf('SR') === 0) {
        return 'sr'
    }
    if(billNo.indexOf('ZZ') === 0) {
        return 'banktran'
    }
    if(billNo.indexOf('ZC') === 0) {
        return 'zc'
    }
    if(billNo.indexOf('PZ') === 0) {
        return 'card'
    }
    return false
}

module.exports = router;